package com.ddz.controller;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * session监听器
 *
 * 用于存储当前活跃的session
 */
@WebListener
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();
        // 从ServletContext获取存储Session的列表，如果不存在则创建一个新的列表
        List<HttpSession> sessionList = (List<HttpSession>) servletContext.getAttribute("sessionList");
        if (sessionList == null) {
            sessionList = new ArrayList<>();
            servletContext.setAttribute("sessionList", sessionList);
        }
        sessionList.add(session);
        System.out.println("添加会话");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("删除会话");
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();
        List<HttpSession> sessionList = (List<HttpSession>) servletContext.getAttribute("sessionList");
        if (sessionList!= null) {
            sessionList.remove(session);
        }
    }
}